package pl.edu.agh.io.gpstracker.client.window;

import pl.edu.agh.io.gpstracker.client.action.SendMessageAction;
import pl.edu.agh.io.gpstracker.client.dto.MessagesDto;
import pl.edu.agh.io.gpstracker.client.dto.UserDto;
import pl.edu.agh.io.gpstracker.client.result.VoidResult;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.TextAreaItem;
import com.smartgwt.client.widgets.form.fields.TextItem;

/**
 * 
 * @author wkedzior
 * 
 */
public class NewMessageWindow extends GenericWindow {

	private UserDto reciver;
	private TextItem title;
	private TextAreaItem content;

	public NewMessageWindow(UserDto reciver) {
		super(250, 200);
		super.setTitle("Wylij wiadomosc");
		this.reciver = reciver;
		init();
	}

	/**
	 * 
	 */
	private void init() {
		content = new TextAreaItem();
		content.setTitle("Tresc");
		content.setRequired(true);
		title = new TextItem();
		title.setTitle("Tytul");
		title.setRequired(true);
		DynamicForm df = new DynamicForm();
		df.setFields(title, content);
		IButton send = new IButton("Wyslij");
		send.setLayoutAlign(Alignment.RIGHT);
		send.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				sendMessage();
			}
		});
		addItem(df);
		addItem(send);
	}

	/**
	 * 
	 */
	private void sendMessage() {
		dispatcher.execute(new SendMessageAction(new MessagesDto(title
				.getValueAsString(), content.getValueAsString(), (short) -1,
				 reciver, LoginWindow.LOGED_USER)),
				new AsyncCallback<VoidResult>() {

					@Override
					public void onFailure(Throwable caught) {
						SC.say(caught.toString());

					}

					@Override
					public void onSuccess(VoidResult res) {
						SC.say("Wiadomosc do uzytkownika <b>"
								+ reciver.getLogin() + "</b> zostala wyslana!");
						
						NewMessageWindow.this.hide();
					}
				});
	}
}
